package io.renren.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.renren.entity.SysUserEntity;
import io.renren.service.SysUserService;
import io.renren.utils.R;
import io.renren.utils.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录相关
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@Controller
public class SysLoginController {
    @Autowired
    private Producer producer;
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("captcha.jpg" )
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache" );
        response.setContentType("image/jpeg" );

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();

        ImageIO.write(image, "jpg", out);
    }

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public R login(String username, String password, String captcha) throws IOException {
        //去掉验证码
        /*String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}*/
        Subject subject = ShiroUtils.getSubject();
        try {

            //sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error(e.getMessage());
        } catch (LockedAccountException e) {
            return R.error(e.getMessage());
        } catch (AuthenticationException e) {
            return R.error("账户验证失败" );
        }
        SysUserEntity user = sysUserService.queryByUserName(username);

        String  ifsuperdept = user.getIfsuperdept();
        List<Long> depts = new ArrayList<>();
        //所在部门及下级权限
        if("ifsuperdept01".equals(ifsuperdept)){
            depts = user.getDeptnoList();
            if(depts!=null&&depts.size()>0) {
                //有值说明非全部权限，如果非主管，则不能看到自己部门的权限，
                //非主管
                if("1".equals(user.getIssupervisor())){
                    for(Long dept:depts){
                        if((dept+"").equals(user.getDeptNo())){
                            depts.remove(dept);
                            break;
                        }

                    }

                }
                if(depts!=null&&depts.size()>0){
                    user.setDeptnoList(depts);
                }else{
                   user.setDeptnoList(null);

                }

            }
        }else{
            //获取所有部门
            List<Long> list = sysUserService.getAllDept("1");
            user.setDeptnoList(list);
        }
        subject.getSession().setAttribute("user", user);

        return R.ok();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }

}
